const utils = require('../../utils/utils')
const Bmob = require('../../utils/bmob')

Page({
  data: {
    newsList: [],
    pageIndex: 0,
    loadingTip: '上拉加载更多',
    mind: true,
    // v1/news/list?offset=0&limit=20
  },
  onLoad() {
    this.loadData()
  },
  loadData() {
    let query = new Bmob.Query('News')
    if (this.data.mind) {
      query.equalTo('mind', true)
    }
    query.descending('createdAt');
    query.skip(this.data.pageIndex * utils.pageSize)
    query.limit(utils.pageSize)
    query.find().then(results => {
      wx.stopPullDownRefresh();
      results.map(item => {
        item.set('createdAt', utils.todayDateTime(item.createdAt))
        return item
      })
      results = utils.formatResults(results)
      let newsList = this.data.newsList
      if (this.data.pageIndex == 0) {
        newsList = []
      }
      newsList = newsList.concat(results)
      console.log(results)
      this.setData({
        newsList: newsList,
        loadingTip: results.length < utils.pageSize ? '已经没有更多啦' : '上拉加载更多'
      })
    })
  },
  onReachBottom() {
    let pageIndex = this.data.pageIndex
    pageIndex++
    this.setData({
      pageIndex: pageIndex
    })
    this.loadData()
  },
  onPullDownRefresh: function () {
    this.refresh()
  },
  onShareAppMessage: function () {
		return {
			title: '消息助手',
			desc: '及时新鲜的区块链新闻',
			path: '/news/index/index'
		}
  },
  mind (e) {
    console.log(e.detail.value)
    this.setData({
      mind: !e.detail.value
    })
    this.refresh()
  },
  refresh () {
    // 下拉刷新
    this.setData({
      pageIndex: 0
    })
    this.loadData();
  }
})
